package cn.stylefeng.guns.modular.financial.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.financial.entity.FinancialIncomeMatching;
import cn.stylefeng.guns.modular.financial.mapper.FinancialIncomeMatchingMapper;
import cn.stylefeng.guns.modular.financial.model.params.FinancialIncomeMatchingParam;
import cn.stylefeng.guns.modular.financial.model.result.FinancialIncomeMatchingResult;
import  cn.stylefeng.guns.modular.financial.service.FinancialIncomeMatchingService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

/**
 * <p>
 * 收入匹配管理表 服务实现类
 * </p>
 *
 * @author zhucx
 * @since 2024-03-27
 */
@Service
public class FinancialIncomeMatchingServiceImpl extends ServiceImpl<FinancialIncomeMatchingMapper, FinancialIncomeMatching> implements FinancialIncomeMatchingService {

    @Override
    public void add(FinancialIncomeMatchingParam param){
        FinancialIncomeMatching entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(FinancialIncomeMatchingParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(FinancialIncomeMatchingParam param){
        FinancialIncomeMatching oldEntity = getOldEntity(param);
        FinancialIncomeMatching newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public FinancialIncomeMatchingResult findBySpec(FinancialIncomeMatchingParam param){
        return null;
    }

    @Override
    public List<FinancialIncomeMatchingResult> findListBySpec(FinancialIncomeMatchingParam param){
        return this.baseMapper.findListBySpec(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(FinancialIncomeMatchingParam param,String condition,Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(FinancialIncomeMatchingParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private FinancialIncomeMatching getOldEntity(FinancialIncomeMatchingParam param) {
        return this.getById(getKey(param));
    }

    private FinancialIncomeMatching getEntity(FinancialIncomeMatchingParam param) {
        FinancialIncomeMatching entity = new FinancialIncomeMatching();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }
    
	private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }
	
	@Resource
    private UserService userService;
	
	@Resource
    private BasicOperateService basicOperateService;

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=150)
	public ResponseData getExceldata(MultipartFile file,  FinancialIncomeMatchingParam financialIncomeMatchingParam, ResponseData data) throws Exception {
		User user = userService.getcurrentUser();
		if (ToolUtil.isEmpty(financialIncomeMatchingParam.getOperateId())) {
			data.setSuccess(false);
			data.setMessage("请选择项目");
			return data;
		}
		BasicOperate basicOperate = basicOperateService.getById(financialIncomeMatchingParam.getOperateId());
		
		String fileName = file.getOriginalFilename();
		List<FinancialIncomeMatching> list = new ArrayList<FinancialIncomeMatching>();
		
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("上传文件格式不正确");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            FinancialIncomeMatching financialIncomeMatching = new FinancialIncomeMatching();
            financialIncomeMatching.setDeptId(user.getDeptId());
            financialIncomeMatching.setDeliverId(user.getDeliverId());
            financialIncomeMatching.setOperateId(financialIncomeMatchingParam.getOperateId());
            financialIncomeMatching.setOperateName(basicOperate.getOperateName());
            financialIncomeMatching.setCreateTime(new Date());
            financialIncomeMatching.setCreateUserName(user.getName());
            financialIncomeMatching.setState("未匹配");

            String  customerOrder = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(customerOrder)) {
            	financialIncomeMatching.setCustomerOrder(customerOrder);
			} else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中客户单号不得为空!");
				return data;
			}
            
            String  freightMoney = getCellValue(row.getCell(1));
            if (ToolUtil.isNotEmpty(freightMoney)) {
            	BigDecimal freightMoneybig = new BigDecimal(freightMoney).setScale(2,BigDecimal.ROUND_DOWN);
            	financialIncomeMatching.setFreightMoney(freightMoneybig.toString());
			} else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中运费不得为空!");
				return data;
			}

            String  hdTime = getCellValue(row.getCell(2));
            if (ToolUtil.isNotEmpty(hdTime)) {
            	financialIncomeMatching.setHdTime(hdTime);
			} else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中回单录入日期不得为空!");
				return data;
			}
            
            String  v1 = getCellValue(row.getCell(3));
            if (ToolUtil.isNotEmpty(v1)) {
            	BigDecimal v1big = new BigDecimal(v1).setScale(4,BigDecimal.ROUND_DOWN);
            	financialIncomeMatching.setV1(v1big+"");
			} 

            list.add(financialIncomeMatching);
        }
        if (list.size() > 0) {
        	this.saveBatch(list);
		}
        data.setSuccess(true);
		return data;
	}

}
